﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace DoublyUtils
{
    public class DirectoryUtils
    {
        private static LogUtils log = LogUtils.getInstance(typeof(DirectoryUtils));

        /// <summary>
        /// 复制文件夹
        /// </summary>
        /// <param name="sourcePath"></param>
        /// <param name="targetPath"></param>
        /// <returns></returns>
        public static Boolean copyDirectory(String sourcePath, String targetPath)
        {
            try
            {
                //源路径不存在，无法复制
                if (!(Directory.Exists(sourcePath)))
                    return false;

                //目标路径不存在，创建路径
                if (!Directory.Exists(targetPath))
                {
                    Directory.CreateDirectory(targetPath);
                }

                //复制文件
                String[] files = Directory.GetFiles(sourcePath);
                foreach (String file in files)
                {
                    File.Copy(file, Path.Combine(targetPath, Path.GetFileName(file)));
                }

                //复制文件夹
                String[] directories = Directory.GetDirectories(sourcePath);
                foreach (String directory in directories)
                {
                    copyDirectory(directory, Path.Combine(targetPath, Path.GetFileName(directory)));
                }
            }
            catch (Exception ex)
            {
                log.error(ex.Message);
                return false;
            }

            return true;
        }


        /// <summary>
        /// 删除文件夹里的内容
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public static Boolean deleteDirectory(String path)
        {
            try
            {
                if (!Directory.Exists(path)) return true;

                //删除文件
                String[] files = Directory.GetFiles(path);
                foreach (String file in files)
                {
                    log.info("delete file:" + file);
                    //new FileInfo(file).Attributes = FileAttributes.Normal;
                    File.Delete(file);
                }

                //递归删除文件夹
                String[] directories = Directory.GetDirectories(path);
                foreach (String directory in directories)
                {
                    log.info("delete directory:" + directory);
                    new DirectoryInfo(directory).Attributes = FileAttributes.Normal;
                    deleteDirectory(directory);
                    Directory.Delete(directory, true);
                }
            }
            catch (Exception ex)
            {
                log.error(ex.Message);
                return false;
            }
            return true;
        }
    }
}
